package com.zhengyao.springbootlearn.controller;

import com.zhengyao.springbootlearn.entity.Article;
import com.zhengyao.springbootlearn.repository.ArticleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Calendar;
import java.util.List;

@Controller
public class IndexController {

    @Autowired
    private ArticleRepository repository;
    /**
     * 每页查询数量
     */
    private static final Integer PAGE_SIZE = 2;

    /**
     * 总页数
     */
    private static final String TOTAL_PAGE = "totalPage";

    /**
     * 当前页
     */
    private static final String CURRENT_PAGE = "currentPage";
    
    @RequestMapping("/index")
    public String toIndex(Model model,@RequestParam(required = false ) Integer pageNo){
        if (pageNo == null) {
            pageNo = 0;
        }
        //每页大小默认为2
        Pageable pageable = PageRequest.of(pageNo,PAGE_SIZE);
        Page<Article> articlePage = repository.findAll(pageable);
        
        model.addAttribute("articleList", articlePage.getContent());
        model.addAttribute(TOTAL_PAGE,articlePage.getTotalPages());
        model.addAttribute(CURRENT_PAGE,articlePage.getPageable().getPageNumber());
       
        return "index";
    }

    
}
